//
//  MBStorySearchViewController.m
//  MiBaoTu
//
//  Created by admin on 16/9/27.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBStorySearchViewController.h"
#import "MBSpaceMyCollectionViewController.h"

#import "MBStoryHotSearchCell.h"

#import "FMManageObject.h"

@interface MBStorySearchViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,MBStoryHotSearchCellDelegate> {
    UITableView                 *_tableView;
    NSMutableArray              *_mutArr;   //历史记录
    NSMutableArray              *_mutHotArr;   //热门搜索
    UITextField                 *_textField;
    UIButton                    *_inputBt;
}

@end

@implementation MBStorySearchViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self loadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _mutArr = [[NSMutableArray alloc]init];
    _mutHotArr = [[NSMutableArray alloc]init];
    // Do any additional setup after loading the view.
    [self setNavBar];
    [self setupUI];
}

- (void)setNavBar
{
    [self setBackItem];
    
    if (ISIPAD) {
        [self setTitleView:@"全部评论"];
        
        [self setRightPlayerItem];
    } else {
        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 620*PERCEN, 60*PERCEN)];
        bgView.backgroundColor = [UIColor clearColor];
        _textField = [[UITextField alloc]initWithFrame:CGRectMake(30*PERCEN, 0, (WIDTH_5S ? 550*PERCEN :590*PERCEN), bgView.height)];
        _textField.placeholder = @" 歌曲 专辑 主播";
        _textField.backgroundColor = [UIColor whiteColor];
        _textField.borderStyle = UITextBorderStyleRoundedRect;
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _textField.attributedPlaceholder = [[NSAttributedString alloc]initWithString:@" 歌曲 专辑 主播" attributes:@{NSForegroundColorAttributeName: UIColorFromHex(0x999999),NSFontAttributeName:[UIFont systemFontOfSize:13.f]}];
        _textField.font = [UIFont systemFontOfSize:13.f];
        _textField.delegate = self;
        [bgView addSubview:_textField];
        self.navigationItem.titleView = bgView;
        
        UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
        bt.frame = CGRectMake(0, 0, 60, 30);
        [bt setTitle:@"搜索" forState:UIControlStateNormal];
        [bt setTitle:@"搜索" forState:UIControlStateHighlighted];
        [bt setTitleEdgeInsets:UIEdgeInsetsMake(-40, 0, -40, -40)];
        bt.titleLabel.font = [UIFont systemFontOfSize:13.f];
        [bt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [bt addTarget:self action:@selector(onSelectItemForWork) forControlEvents:UIControlEventTouchUpInside];
        [self setRightBarItems:bt];
    }
}

- (void)setupUI {
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.view.height) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_tableView];
    _tableView.tableFooterView = [self addTableFootView];
    if (ISIPAD) {
        _tableView.tableHeaderView = [self addTableHeaderView];
    }
}

- (void)onUpdateUIForView:(UIDeviceOrientation)orientation
{
    _tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.view.height);
    _tableView.tableFooterView = [self addTableFootView];
    if (ISIPAD) {
        _tableView.tableHeaderView = [self addTableHeaderView];
    }
    [_tableView reloadData];
}

- (UIView *)addTableFootView
{
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40+120*PERCEN)];
    bgView.backgroundColor = [UIColor clearColor];
    
    UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
    bt.frame = CGRectMake(0, 60*PERCEN, bgView.width, 40);
    [bt setTitle:@"清除搜索历史" forState:UIControlStateNormal];
    [bt setTitle:@"清除搜索历史" forState:UIControlStateHighlighted];
    bt.titleLabel.font = [UIFont systemFontOfSize:13.f];
    [bt setTitleColor:UIColorFromHex(0x333333) forState:UIControlStateNormal];
    [bt addTarget:self action:@selector(onSelectItemForClear) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:bt];
    
    return bgView;
}

- (UIView *)addTableHeaderView
{
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 130*PERCEN)];
    bgView.backgroundColor = [UIColor clearColor];
    _textField = [[UITextField alloc]initWithFrame:CGRectMake(50*PERCEN, 30*PERCEN, SCREEN_WIDTH-100*PERCEN, bgView.height-30*PERCEN)];
    _textField.backgroundColor = [UIColor whiteColor];
    _textField.borderStyle = UITextBorderStyleRoundedRect;
    _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textField.font = [UIFont systemFontOfSize:13.f];
    _textField.delegate = self;
    [bgView addSubview:_textField];
    
    _inputBt = [UIButton buttonWithType:UIButtonTypeCustom];
    _inputBt.frame = _textField.frame;
    [_inputBt setTitle:@"歌曲 专辑 亲子秀" forState:UIControlStateNormal];
    [_inputBt setTitleColor:UIColorFromHex(0x999999) forState:UIControlStateNormal];
    _inputBt.titleLabel.font = [UIFont systemFontOfSize:14.f];
    [_inputBt setImage:[UIImage imageNamed:@"sousuo2"] forState:UIControlStateNormal];
    [_inputBt addTarget:self action:@selector(onTapActionForSerch) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:_inputBt];
    
    return bgView;
}

//加载数据
- (void)loadData
{
    //搜索历史
    UserModel *model = [UserManager standerDefult].userModel;
    if (model) {
        FMManageObject *manager = [FMManageObject standerDefault];
        NSArray *arr = [manager SelectTableBySearchHistoryWithContent:@"" withName:[NSString stringWithFormat:@"%@",model.UserID]];
        [_mutArr removeAllObjects];
        for (NSDictionary *dic in arr) {
            NSString *content = [dic objectForKey:@"content"];
            [_mutArr addObject:content];
        }
    }
    if (_mutArr.count == 0) {
         _tableView.tableFooterView = nil;
    }
    [_tableView reloadData];
    //热搜索
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString *url = [NSString stringWithFormat:STORY_HOT_KEY_URL_PATH];
    [[HTTPManager standerDefault]AFGetRequest:url view:nil success:^(id json) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        if ([json isKindOfClass:[NSDictionary class]]) {
            if ([json[@"ret_code"] intValue] == 0) {
                NSArray *arr = json[@"data"];
                if ([arr isKindOfClass:[NSArray class]]) {
                    [_mutHotArr removeAllObjects];
                    for (NSDictionary *dic in arr) {
                        NSString *title = [dic objectForKey:@"HotKey"];
                        [_mutHotArr addObject:title];
                    }
                    [_tableView reloadData];
                }
            }
        }
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    }];
}

#pragma mark -播放器
- (void)onSelectItemForPlay
{
  
}

- (void)back
{
    [self onHideKeyBoard];
    [super back];
}

- (void)onTapActionForSerch
{
    _inputBt.hidden = YES;
    [_textField becomeFirstResponder];
    _textField.placeholder = @" 歌曲 专辑 亲子秀";
    _textField.attributedPlaceholder = [[NSAttributedString alloc]initWithString:@" 歌曲 专辑 亲子秀" attributes:@{NSForegroundColorAttributeName: UIColorFromHex(0x999999),NSFontAttributeName:[UIFont systemFontOfSize:13.f]}];
}

#pragma mark - 跳转搜索结果页面
- (void)onSelectItemForWork
{
     [self onHideKeyBoard];
    
    if (_textField.text.length > 0) {
        [self onTureToNextController:_textField.text];
    }
}

- (void)onTureToNextController:(NSString *)text
{
    //插入数据入数据库
    UserModel *model = [UserManager standerDefult].userModel;
    if (model) {
        FMManageObject *manager = [FMManageObject standerDefault];
        NSArray *arr = [manager SelectTableBySearchHistoryWithContent:[NSString stringWithFormat:@"%@",text] withName:[NSString stringWithFormat:@"%@",model.UserID]];
        if (arr.count == 0) {
            arr = [manager onSelectSearchHistoryCount];
            [[FMManageObject standerDefault]insertTableBySearchHistoryWithId:[NSString stringWithFormat:@"%d",(int)arr.count+1] withName:[NSString stringWithFormat:@"%@",model.UserID] withContent:text];
        }
    }
    
    MBSpaceMyCollectionViewController *collection = [[MBSpaceMyCollectionViewController alloc]init];
    collection.type = MBSpaceMyCollectionShowType_Search;
    collection.searchText = text;
    [self.navigationController pushViewController:collection animated:YES];
}

#pragma mark - 清除搜索历史
- (void)onSelectItemForClear
{
    UserModel *model = [UserManager standerDefult].userModel;
    if (model && _mutArr.count > 0) {
        FMManageObject *manager = [FMManageObject standerDefault];
        [manager deleteBySearchHistoryFile:[NSString stringWithFormat:@"%@",model.UserID]];
        [_mutArr removeAllObjects];
        [_tableView reloadData];
    }
}

#pragma mark -返回按钮键盘隐藏
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [self onHideKeyBoard];
    if (_textField.text.length > 0) {
        //插入数据入数据库
        //        BOOL iss = [[FMManageObject standerDefault]insertTableBySearchHistoryWithId:@"2" withName:@"188" withContent:@"猫猫2"];
        
        MBSpaceMyCollectionViewController *collection = [[MBSpaceMyCollectionViewController alloc]init];
        collection.type = MBSpaceMyCollectionShowType_Search;
        [self.navigationController pushViewController:collection animated:YES];
    }

    return YES;
}

- (void)onHideKeyBoard
{
    [_textField resignFirstResponder];
    [self.view endEditing:YES];
}

#pragma mark - 热门搜索
- (void)onSelectItemForHotSearch:(MBStoryHotSearchCell *)view withSelectIndex:(int)index
{
    [self onHideKeyBoard];
    
    NSString *text = [_mutHotArr objectAtIndex:index];
    if (text.length > 0) {
        [self onTureToNextController:text];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    return _mutArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        static NSString *cellID = @"story_hot_search_cell";
        MBStoryHotSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[MBStoryHotSearchCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.backgroundColor = [UIColor clearColor];
            cell.backgroundView = nil;
            cell.delegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.orientation = self.orientation;
        [cell layoutData:_mutHotArr];
        
        return cell;
    }
    
    static NSString *cellID = @"story_search_history_cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        cell.backgroundView = nil;
        
        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 80*PERCEN)];
        bgView.backgroundColor = [UIColor whiteColor];
        bgView.tag = 199;
        [cell.contentView addSubview:bgView];
        
        //标题
        UILabel *_nickNameLb = [[UILabel alloc]initWithFrame:CGRectMake(25*PERCEN, (80*PERCEN-20)/2., 200, 20)];
        _nickNameLb.backgroundColor = [UIColor clearColor];
        _nickNameLb.textAlignment = NSTextAlignmentLeft;
        _nickNameLb.textColor = UIColorFromHex(0x333333);
        _nickNameLb.font = [UIFont systemFontOfSize:13.f];
        _nickNameLb.tag = 200;
        [bgView addSubview:_nickNameLb];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 80*PERCEN-1, SCREEN_WIDTH, 1)];
        lineView.backgroundColor = [UIColorFromHex(0x999999)colorWithAlphaComponent:.35];
        lineView.tag = 201;
        [bgView addSubview:lineView];
    }
    UIView *bgView = (UIView *)[cell viewWithTag:199];
    UILabel *nickNameLb = (UILabel *)[cell viewWithTag:200];
    UIView *lineView = (UIView *)[cell viewWithTag:201];
    
    nickNameLb.text = [_mutArr objectAtIndex:indexPath.row];
    if (indexPath.row == _mutArr.count-1) {
        lineView.hidden = YES;
    } else {
        lineView.hidden = NO;
    }
    if (ISIPAD) {
        bgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 100*PERCEN);
        nickNameLb.frame = CGRectMake(460*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.), ((ISIPAD?100*PERCEN:80*PERCEN)-20)/2., 200, 20);
        lineView.frame = CGRectMake(440*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.), (ISIPAD?100*PERCEN:80*PERCEN)-1, SCREEN_WIDTH-880*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.), 1);
    } else {
        bgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 100*PERCEN);
        nickNameLb.frame = CGRectMake(25*PERCEN, (80*PERCEN-20)/2., 200, 20);
        lineView.frame = CGRectMake(0, 80*PERCEN-1, SCREEN_WIDTH, 1);
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {

        if (_mutHotArr.count > 0) {
            UIFont *font = [UIFont systemFontOfSize:13.f];
            float allWidth = (ISIPAD?460*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.):35*PERCEN);
            float allHeight = 20*PERCEN;
            int index = 0; //保存换行次数
            for (int i=0; i<_mutHotArr.count; i++) {
                NSString *title = [_mutHotArr objectAtIndex:i];
                float itemWidth = [title boundingRectWithSize:CGSizeMake(1000, 70*PERCEN) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:NULL].size.width+(WIDTH_5S ? 20 :30);
                //frame
               if (allWidth+itemWidth+(ISIPAD?460*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.):35*PERCEN) > SCREEN_WIDTH) {
                    //换行
                    allWidth = (ISIPAD?460*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.):35*PERCEN);
                    
                    ++index;
                    allHeight += (90*PERCEN*index);
                }
                //加上间距
                allWidth += itemWidth+30*PERCEN;
            }
            return allHeight + 110*PERCEN;
        }
        return 0;
        
    }
    return (ISIPAD?100*PERCEN:80*PERCEN);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30*PERCEN+20)];
    bgView.backgroundColor = UIColorFromHex(0xf5f5f5);
    
    //标题
    UILabel *_nickNameLb = [[UILabel alloc]initWithFrame:CGRectMake((ISIPAD?440*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.):25*PERCEN), 15*PERCEN, 200, 20)];
    _nickNameLb.backgroundColor = [UIColor clearColor];
    _nickNameLb.textAlignment = NSTextAlignmentLeft;
    _nickNameLb.textColor = UIColorFromHex(0x333333);
    _nickNameLb.font = [UIFont systemFontOfSize:13.f];
    [bgView addSubview:_nickNameLb];
    if (section == 0) {
        _nickNameLb.text = @"热门搜索";
    }
    else if (section == 1) {
        _nickNameLb.text = @"搜索历史";
    }
    
    return bgView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return (30*PERCEN+20);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [self onHideKeyBoard];
    
    if (indexPath.section == 0) {
        return;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *text = [_mutArr objectAtIndex:indexPath.row];
    if (text.length > 0) {
        [self onTureToNextController:text];
    }
}

@end
